<template>
  <div class="patient-list-container">
    <div class="page-header">
      <h2>患者档案管理</h2>
      <div class="header-actions">        
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索条件 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :model="searchForm" label-width="80px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="患者姓名">
                <el-input
                  v-model="searchForm.patientName"
                  placeholder="请输入患者姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="手机号">
                <el-input
                  v-model="searchForm.phoneNumber"
                  placeholder="请输入手机号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="就诊状态">
                <el-select
                  v-model="searchForm.visitStatus"
                  placeholder="请选择"
                  clearable
                >
                  <el-option label="待就诊" value="waiting" />
                  <el-option label="就诊中" value="in_consultation" />
                  <el-option label="已完成" value="completed" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="就诊日期">
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="form-actions">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 患者列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>患者信息</span>
          <span class="total-count">共 {{ total }} 条记录</span>
        </div>
      </template>

      <div class="table-wrapper">
        <el-table
          :data="patientList"
          v-loading="loading"
          style="width: 100%"
          @row-click="handleRowClick"
          :scrollbar-always-on="true"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column prop="patient_name" label="患者姓名" min-width="120">
            <template #default="{ row }">
              <div class="patient-name-cell">
                <el-avatar :size="32" :src="row.avatar" class="patient-avatar">
                  {{ getAvatarText(row.patient_name) }}
                </el-avatar>
                <span class="name-text">{{ row.patient_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="gender" label="性别" width="80" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.gender === '男' ? 'primary' : 'danger'"
                size="small"
              >
                {{ row.gender }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80" align="center" />
          <el-table-column prop="phone_number" label="手机号" min-width="130" />
          <el-table-column
            prop="latest_visit_time"
            label="最近就诊"
            min-width="120"
          >
            <template #default="{ row }">
              {{ formatDate(row.latest_visit_time) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="record_count"
            label="完成病历"
            width="100"
            align="center"
          >
            <template #default="{ row }">
              <el-tag type="info" size="small">
                {{ row.record_count }} 次
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="visit_status"
            label="当前状态"
            min-width="100"
            align="center"
          >
            <template #default="{ row }">
              <el-tag
                :type="getStatusType(row.latest_visit_status)"
                size="small"
              >
                <!-- 修改这里 -->
                {{ getStatusText(row.latest_visit_status) }}
                <!-- 修改这里 -->
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="200"
            fixed="right"
            align="center"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleViewRecords(row)"
                >
                  查看病历
                </el-button>
                <el-button
                  type="success"
                  link
                  size="small"
                  @click.stop="handleStartDiagnosis(row)"
                  :disabled="row.latest_visit_status !== 'waiting'"
                >
                  开始诊断
                </el-button>
                <el-button
                  type="info"
                  link
                  size="small"
                  @click.stop="handleViewDetail(row)"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 患者详情抽屉 -->
    <PatientDetailDrawer
      v-model="detailDrawerVisible"
      :patient-id="selectedPatientId"
      :patient-info="patientList.find(p => p.patient_id === selectedPatientId)"
      @diagnosis-started="handleDiagnosisStarted"
      @view-records="handleViewRecordsFromDrawer"
    />

    <!-- 病历总览抽屉 -->
    <MedicalRecordOverview
      v-model="recordOverviewVisible"
      :patient-id="selectedPatientId"
      :patient-info="patientList.find(p => p.patient_id === selectedPatientId)"
      @record-selected="handleRecordSelected"
    />

    <!-- 病历详情对话框 -->
    <MedicalRecordDetail
      v-model="recordDetailVisible"
      :record-id="selectedRecordId"
      :record-data="selectedRecordData"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import PatientDetailDrawer from "@/components/doctor/PatientDetailDrawer.vue";
import MedicalRecordOverview from "@/components/doctor/MedicalRecordOverview.vue";
import MedicalRecordDetail from "@/components/doctor/MedicalRecordDetail.vue";
import { useStore } from "vuex";
// 引入后端API
import { getPatientMasterPagerDataByDoctorSearch } from "@/api/doctor.js";

const store = useStore();
// 响应式数据
const loading = ref(false);
const total = ref(0);
const selectedPatientId = ref(null);
const selectedRecordId = ref(null);
const selectedRecordData = ref(null); // 新增：存储选中的病历数据
const detailDrawerVisible = ref(false);
const recordOverviewVisible = ref(false);
const recordDetailVisible = ref(false);

// 搜索表单
const searchForm = reactive({
  patientName: "",
  phoneNumber: "",
  visitStatus: "",
  dateRange: [],
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pagetotal: 0,
});

// 医生ID - 实际项目中应该从用户信息中获取
const doctorId = store.state.user?.user_id;

// 患者列表数据
const patientList = ref([]);

// 计算属性：获取查询参数
const queryParams = computed(() => {
  const params = {
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
    doctor_id: doctorId,
    patient_name: searchForm.patientName,
    phone_number: searchForm.phoneNumber,
    visit_status: searchForm.visitStatus,
    startDate: "",
    endDate: "",
  };

  // 处理日期范围
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    params.startDate = searchForm.dateRange[0];
    params.endDate = searchForm.dateRange[1];
  }

  return params;
});

// 方法
const handleSearch = () => {
  pagination.currentPage = 1;
  loadPatientList();
};

const handleReset = () => {
  Object.assign(searchForm, {
    patientName: "",
    phoneNumber: "",
    visitStatus: "",
    dateRange: [],
  });
  handleSearch();
};

const loadPatientList = async () => {
  loading.value = true;
  try {
    // 构建API请求参数
    const requestParams = {
      ...queryParams.value,
    };

    // TODO: 调用API获取患者列表
    const response = await getPatientMasterPagerDataByDoctorSearch(
      requestParams
    );
    console.log("患者列表响应：", response);
    if (response && response.code == 200) {
      patientList.value = response.data.data.map((patient) => ({
        ...patient,
        avatar: "", // 可以根据需要添加头像URL
        id: patient.patient_id,
      }));
      total.value = response.data.total;
      pagination.total = response.data.total;
      pagination.pagetotal = response.data.pageTotal;
    } else {
      ElMessage.error(response.message || "获取患者列表失败");
    }
  } catch (error) {
    console.error("获取患者列表失败:", error);
    ElMessage.error("获取患者列表失败");
  } finally {
    loading.value = false;
  }
};

const refreshData = async () => {
  await loadPatientList();
  ElMessage.success("数据已刷新");
};

const handleRowClick = (row) => {
  selectedPatientId.value = row.patient_id;
  detailDrawerVisible.value = true;
};

const handleViewRecords = (row) => {
  selectedPatientId.value = row.patient_id;
  recordOverviewVisible.value = true;
};

const handleStartDiagnosis = (row) => {
  selectedPatientId.value = row.patient_id;
  // TODO: 跳转到诊断页面或打开诊断对话框
  ElMessage.info(`开始为 ${row.patient_name} 进行诊断`);
};

const handleViewDetail = (row) => {
  selectedPatientId.value = row.patient_id;
  detailDrawerVisible.value = true;
};

const handleRecordSelected = (record) => {
  selectedRecordId.value = record.diagnosis_id;
  // 存储病历数据
  selectedRecordData.value =  record;
  recordDetailVisible.value = true;
  recordOverviewVisible.value = false;
};

const handleDiagnosisStarted = (patientId) => {
  ElMessage.success("诊断已开始");
  refreshData();
  // 关闭抽屉
  detailDrawerVisible.value = false;
};

const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadPatientList();
};

const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadPatientList();
};

//查看完整简历
const handleViewRecordsFromDrawer = (patientId) => {
  selectedPatientId.value = patientId;
  recordOverviewVisible.value = true;
};

const formatDate = (dateString) => {
  if (!dateString) return "-";
  return dateString; // 实际项目中可以使用dayjs或moment格式化
};

const getStatusType = (status) => {
  const typeMap = {
    waiting: "warning",
    in_consultation: "primary", // 修改这里
    completed: "success",
  };
  return typeMap[status] || "info";
};

const getStatusText = (status) => {
  const textMap = {
    waiting: "待就诊",
    in_consultation: "就诊中", // 修改这里
    completed: "已完成",
  };
  return textMap[status] || status;
};

// 安全获取头像文本
const getAvatarText = (patientName) => {
  if (!patientName || typeof patientName !== "string") {
    return "?";
  }
  return patientName.charAt(0);
};

// 生命周期
onMounted(() => {
  loadPatientList();
});
</script>

<style lang="scss" scoped>
.patient-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.search-card {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.search-form {
  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 10px;
  }
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.table-wrapper {
  flex: 1;
  overflow: auto;

  :deep(.el-table) {
    min-width: 900px; // 确保表格有最小宽度，在小屏幕上可以横向滚动
  }
}

.patient-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.patient-avatar {
  background: #409eff;
  color: white;
  font-weight: 500;
  flex-shrink: 0;
}

.name-text {
  font-weight: 500;
  word-break: keep-all;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  flex-shrink: 0;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .patient-list-container {
    padding: 15px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;

    .header-actions {
      width: 100%;
      justify-content: flex-start;
    }
  }

  .search-form .form-actions {
    justify-content: center;
  }

  .pagination-container {
    justify-content: center;

    :deep(.el-pagination) {
      flex-wrap: wrap;
      justify-content: center;
    }
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}

@media (max-width: 480px) {
  .patient-list-container {
    padding: 10px;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>